package com.ptswitch.material.pages.contract;

import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.ioc.annotations.Inject;

import com.ptswitch.material.model.contract.Contract;
import com.ptswitch.material.model.contract.ContractItem;
import com.ptswitch.material.pages.base.PageBase;
import com.ptswitch.material.service.ContractItemService;
import com.ptswitch.material.service.ContractService;
import com.ptswitch.material.util.security.PermissionUtil;

public class ViewItem extends PageBase {
    @Inject
    private ContractService contractSer;
    @Inject
    private ContractItemService contractItemSer;
    @Property
    private ContractItem contractItem;
    private long id;
    @Property
    private boolean updateMoreButton = false;
    @InjectPage
    private ViewContract viewContract;

    Object withInit(long id) {
        this.id = id;
        return this;
    }

    @OnEvent(value = EventConstants.ACTIVATE)
    Object init(long id) {
        checkPermitted(PermissionUtil.ContractItemView);
        withInit(id);
        contractItem = contractItemSer.findById(id);
        return null;
    }

    @OnEvent(value = EventConstants.PASSIVATE)
    Object onPassivate() {
        return id;
    }

    @SetupRender
    Object display() {
        return null;
    }

    @OnEvent(value = EventConstants.SUCCESS, component = "update")
    Object update() {
        checkPermitted(PermissionUtil.ContractItemEdit);
        contractItem.computePrice();
        contractItemSer.save(contractItem);
        //update contract total price
        Contract contract = contractSer.findById(contractItem.getContract().getId(), ContractService.Init_Items);
        contract.updateForItem();
        contractSer.save(contract);
        setMessage("修改成功");
        return null;
    }

    @OnEvent(component = "delete")
    Object delete() {
        checkPermitted(PermissionUtil.ContractItemDelete);
        contractItemSer.delete(contractItem);
        //update contract total price
        Contract contract = contractSer.findById(contractItem.getContract().getId(), ContractService.Init_Items);
        contract.updateForItem();
        contractSer.save(contract);
        setMessage("删除成功");
        return viewContract.withInit(contract.getId());
    }

}
